package com.hznu.coursemanagerbackend.modules.sys.service.base;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hznu.coursemanagerbackend.modules.sys.entity.Attendexam;
import com.hznu.coursemanagerbackend.modules.sys.entity.Exam;
import com.hznu.coursemanagerbackend.modules.sys.service.AttendexamService;
import com.hznu.coursemanagerbackend.modules.sys.service.ExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
@EnableScheduling
public class SchedulingService {

    @Autowired
    ExamService examService;
    @Autowired
    AttendexamService attendexamService;

    @Scheduled(fixedRate = 2000)
    private void examState()
    {
        Date currentTiem = new Date(System.currentTimeMillis());
        List<Exam> exams = examService.selectList(new EntityWrapper<>());
        for(Exam exam : exams)
        {
            Date start = exam.getStarttime();
            Date finish = exam.getFinishtime();
            if(currentTiem.before(start)&&exam.getState()!=1)
            {
                exam.setState(1);
                examService.updateById(exam);
            }else if((currentTiem.equals(start)||currentTiem.after(exam.getStarttime()))&&(currentTiem.equals(finish)||currentTiem.before(finish))&&exam.getState()!=2)
            {
                exam.setState(2);
                attendexamService.initRemain(exam);
                examService.updateById(exam);
            }else if(currentTiem.after(finish)&&exam.getState()!=3)
            {
                exam.setState(3);
                examService.updateById(exam);
            }
        }
        System.out.println("ExamState update!");
    }

}
